#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <time.h>
#include <unistd.h>

#include "log.h"

#define LOG_FILE "./LOG"
#define HOSTLEN 256
#define BACKLOG 1
#define BUSIZE 1024

#define oops(msg) {perror(msg);}
#define oops_exit(msg) {perror(msg); exit(1);}

int make_server_socket(int portnum, int backlog)
{
	struct sockaddr_in addr;
	int sock_fd;

	memset((void*)&addr, 0, sizeof(addr));
	sock_fd = socket(AF_INET, SOCK_STREAM, 0);
	if(sock_fd==-1)
	{
		write_log(LOG_DEBUG, LOG_FILE, "%s", "Create socket error...");
		oops("Create socket error...");
		close(sock_fd);
		return -1;
	}

	addr.sin_addr.s_addr = inet_addr(INADDR_ANY);
	addr.sin_family = AF_INET;
	addr.sin_port = htons(portnum);

	if(bind(sock_fd, (struct sockaddr*)&addr, sizeof(addr))==-1)
	{
		write_log(LOG_DEBUG, LOG_FILE, "%s", "Bind socket error...");
		oops("Create Socket error...");
		close(sock_fd);
		return -1;
	}

	if(listen(sock_fd, backlog)==-1)
	{
		write_log(LOG_DEBUG, LOG_FILE, "%s", "Listen error...");
		oops("Listen error...");
		close(sock_fd);
		return -1;
	}

	return sock_fd;
}


int main(int argc, char **argv)
{
	if(argc==1)
	{
		write_log(LOG_DEBUG, LOG_FILE, "%s", "param error...");
		oops_exit("param error...");
	}

	int sockfd = make_server_socket(atoi(argv[1], BACKLOG));
	if(sockfd==-1)
	{
		write_log(LOG_DEBUG, LOG_FILE, "%s", "make server error...");
		oops_exit("make server error...");
	}

	char request[BUFSIZE] = {0};

	while(1)
	{
		int fd = accept(sockfd, NULL, NULL);
		if(fd==-1)
		{
			write_log(LOG_DEBUG, LOG_FILE, "%s", "Accept error...");
			oops_exit("Accept error...");
		}

		read(fd, (void*)request, sizeof(request));

		printf("got a call: request = %s", request);

		process_rq(reaquest, fd);
		close(fd);
	}

	close(sock_fd);
	return 0;
	

}







































